package com.inno.subject.domain.websocket;

import cn.hutool.core.collection.CollectionUtil;
import com.inno.auth.entity.AuthUserDTO;
import com.inno.subject.common.error.BusinessException;
import com.inno.subject.domain.utils.ApplicationContextUtil;
import com.inno.subject.infra.rpc.UserRpc;
import jakarta.websocket.HandshakeResponse;
import jakarta.websocket.server.HandshakeRequest;
import jakarta.websocket.server.ServerEndpointConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @author sean
 */
@Slf4j
@Component
public class WebSocketConfigurator extends ServerEndpointConfig.Configurator {
    public WebSocketConfigurator(){
        log.info("WebSocketConfigurator初始化");
    }
    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {

        Map<String, List<String>> parameterMap = request.getParameterMap();

        List<String> userIdList = parameterMap.get("userId");
        if (CollectionUtil.isEmpty(userIdList)) {
            log.warn("WebSocket拒绝连接 userId无效");
            throw new BusinessException("WebSocket拒绝连接,userId参数无效或未登录");
        }
        String userIdStr = userIdList.get(0);

        Long userId = Long.valueOf(userIdStr);

        AuthUserDTO authUserDTO = new AuthUserDTO();
        authUserDTO.setId(userId);
        UserRpc userRpc = ApplicationContextUtil.getBean(UserRpc.class);
        Boolean isLogin = userRpc.checkLogin(authUserDTO);
        if (!isLogin) {
            log.warn("WebSocket拒绝连接,userId:{}参数无效或未登录", userId);
            throw new BusinessException("WebSocket拒绝连接,userId参数无效或未登录");
        }
        super.modifyHandshake(sec, request, response);
    }

    @Override
    public boolean checkOrigin(String originHeaderValue) {
        return true;
    }
}